package p.gae.jce.agent;

import java.io.File;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.ProtectionDomain;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

public class AgentMain {
	public static void premain(String agentArgs, Instrumentation inst) {
		try {
			File mvn = new File("C:\\Users\\Panxiaobo\\.m2\\repository");
			File rname = new File("E:\\pxb\\workspace\\p-libs\\p-rename\\target\\p-rename-1.0.jar");
			File asm = new File(mvn, "asm\\asm-debug-all\\3.2\\asm-debug-all-3.2.jar");
			File collections = new File(mvn,
					"commons-collections\\commons-collections\\3.2.1\\commons-collections-3.2.1.jar");
			File io = new File(mvn, "commons-io\\commons-io\\2.0\\commons-io-2.0.jar");
			URLClassLoader cl = new URLClassLoader(new URL[] { rname.toURI().toURL(), asm.toURI().toURL(),
					io.toURI().toURL(), collections.toURI().toURL() }, AgentMain.class.getClassLoader());
			Class<?> reOwnerClz = cl.loadClass("p.rn.owner.ReOwner");
			final Object reOwnerObj = reOwnerClz.newInstance();
			final Method reOwnerOneMethod = reOwnerClz.getDeclaredMethod("reOwnerOne", String.class, byte[].class);
			// Set<String> whitList = new HashSet<String>();
			// Class<?> fileUtilsClz =
			// cl.loadClass("org.apache.commons.io.FileUtils");
			// List<String> list = (List<String>)
			// fileUtilsClz.getDeclaredMethod("readLines", File.class,
			// String.class)
			// .invoke(null, "UTF-8");
			// whitList.addAll(list);
			InputStream is = null;
			try {
				JarFile jce = new JarFile("E:\\pxb\\workspace\\p-libs\\p-gae-jce\\target\\p-gae-jce-1.0.jar");
				is = jce.getInputStream(new ZipEntry("ReOwner.properties"));
				Method m = reOwnerClz.getDeclaredMethod("withConfig", InputStream.class);
				m.invoke(reOwnerObj, is);
			} finally {
				try {
					is.close();
				} catch (Exception ignore) {
				}
			}

			inst.addTransformer(new ClassFileTransformer() {

				@Override
				public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
						ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
					if (loader == null)
						return classfileBuffer;
					try {
						return (byte[]) reOwnerOneMethod.invoke(reOwnerObj, className, classfileBuffer);
					} catch (Exception e) {
						throw new RuntimeException(e);
					}
				}
			});
		} catch (Exception e1) {
			throw new RuntimeException(e1);
		}
	}
}
